﻿using System;
using System.Collections.Generic;
using System.Diagnostics.Eventing.Reader;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SportsStore.Domain.Abstract;
using SportsStore.Domain.Entities;
using SportsStore.WebUI.Models;

namespace SportsStore.WebUI.Controllers
{
    public class ProductController : Controller
    {
        private IProductsRepository repository;
        public int PageSize = 4; //用于分页 by 逐浪cms发哥 2020年09月11日,08:12

        public ProductController(IProductsRepository productsRepository)
        {
            this.repository = productsRepository;
        }

        /*
                //原默认方法，接下来需要更新方法，使之支持分页细节
                //TODO:分页方法：/?page=2    by 逐浪cms发哥 2020年09月15日,07:39
                public ViewResult List(int page = 1)
                {
                    return View(repository.Products
                        .OrderBy(p => p.ProductID)
                        .Skip((page - 1) * PageSize)
                        .Take(PageSize));
                }

        */

        public ViewResult List(string category, int page = 1)
        {
            ProductsListViewModel model = new ProductsListViewModel
            {
                Products = repository.Products
                .Where(p => category == null || p.Category == category)
                .OrderBy(p => p.ProductID)
                .Skip((page - 1) * PageSize)
                .Take(PageSize),
                PagingInfo = new PagingInfo
                {
                    CurrentPage = page,
                    ItemsPerPage = PageSize,
                    TotalItems = category == null ?
                repository.Products.Count() :
                repository.Products.Where(e => e.Category == category).Count()
                },
                CurrentCatgory=category
            };
            return View(model);
        }

        public FileContentResult GetImage(int productId)
        {
            Product prod = repository.Products.FirstOrDefault(p => p.ProductID == productId);
            if (prod!=null)
            {
                return File(prod.ImageData, prod.ImageMimeType);
            }
            else
            {
                return null;
            }
        }

        /* 
         //第一步直接出列表的方法 
        public ViewResult List()
        {
            return View(repository.Products);
        }
        */
        // GET: Product
        //public ActionResult Index()
        //{
        //    return View();
        //}
    }
}